<template>
  <el-drawer :title="title" v-model="dialogVisible" :destroy-on-close="true">
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input placeholder="请输入用户姓名" v-model="userParams.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请输入用户昵称" v-model="userParams.name" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请输入用户密码" v-model="userParams.password" />
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save" v-loading="loading">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref, computed, reactive } from 'vue'
  import type { User } from '@/api/acl/user/type'
  import type { FormInstance, FormRules } from 'element-plus'
  import { reqAddOrUpdate } from '@/api/acl/user'
  import { getElMessage } from '@/utils/message'
  const $emits = defineEmits(['reload'])

  const dialogVisible = ref<boolean>(false)
  const formRef = ref<FormInstance>()
  const loading = ref<boolean>(false)
  const curUserName = ref<string>(localStorage.getItem('curUserName') || '')
  let userParams = ref<User>({
    username: '',
    name: '',
    password: '',
  })
  function validateUserName(_rule: any, value: any, callback: any) {
    if (value) {
      if (value.trim().length >= 5) {
        callback()
      } else {
        callback(new Error('用户名长度至少5位'))
      }
    } else {
      callback(new Error('请输入用户名'))
    }
  }
  function validateName(_rule: any, value: any, callback: any) {
    if (value) {
      if (value.trim().length >= 5) {
        callback()
      } else {
        callback(new Error('用户昵称长度至少5位'))
      }
    } else {
      callback(new Error('请输入用户昵称'))
    }
  }
  function validatePassword(_rule: any, value: any, callback: any) {
    if (value) {
      if (value.trim().length >= 6) {
        callback()
      } else {
        callback(new Error('用户密码长度至少5位'))
      }
    } else {
      callback(new Error('请输入用户密码'))
    }
  }
  const rules = reactive<FormRules<User>>({
    username: [{ required: true, trigger: 'blur', validator: validateUserName }],
    name: [{ required: true, trigger: 'blur', validator: validateName }],
    password: [{ required: true, trigger: 'blur', validator: validatePassword }],
  })
  const title = computed(() => (userParams?.value.id ? '编辑用户' : '新增用户'))
  function open(user: User) {
    userParams.value = JSON.parse(JSON.stringify(user))
    dialogVisible.value = true
  }

  async function save() {
    await formRef.value?.validate(async (valid) => {
      if (!valid) return

      try {
        loading.value = true
        const res: any = await reqAddOrUpdate(userParams.value)
        if (res.code === 200) {
          getElMessage(userParams.value.id ? '编辑用户成功' : '添加用户成功', 'success')
          if (userParams.value.id && curUserName.value === userParams.value.username) {
            // 如果修改的自己的账号，重新刷新页面，项目会在请求请求拦截器中的路由守卫
            window.location.reload()
          }
        } else {
          getElMessage(userParams.value.id ? '编辑用户失败' : '添加用户失败', 'error')
        }
      } catch (error) {
        getElMessage((error as Error).message, 'error')
      } finally {
        dialogVisible.value = false
        loading.value = false
        $emits('reload', { isEdit: !!userParams.value.id })
      }
    })
  }

  function cancel() {
    dialogVisible.value = false
  }

  defineExpose({
    open,
    formRef,
  })
</script>

<style lang="scss" scoped></style>
